
package com.jf.cloud.product.controller.admin;

import cn.hutool.core.collection.CollUtil;
import com.jf.cloud.api.auth.constant.SysTypeEnum;
import com.jf.cloud.api.product.constant.CategoryLevel;
import com.jf.cloud.common.constant.Constant;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.i18n.I18nMessage;
import com.jf.cloud.common.product.vo.CategoryVO;
import com.jf.cloud.common.product.vo.app.CategoryAppVO;
import com.jf.cloud.common.response.ResponseEnum;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.common.security.AuthUserContext;
import com.jf.cloud.common.util.ExcelUtil;
import com.jf.cloud.product.dto.CategoryDTO;
import com.jf.cloud.product.service.CategoryService;
import com.jf.cloud.product.vo.CategoryExcelVO;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 分类信息
 *
 * @author zz
 * @date 2020-10-28 15:27:24
 */
@RestController("adminCategoryController")
@RequestMapping("/mp/category")
@Tag(name = "admin-分类信息")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private MapperFacade mapperFacade;

    @GetMapping
    @Operation(summary = "获取分类信息" , description = "根据categoryId获取分类信息")
    public ServerResponseEntity<CategoryVO> getByCategoryId(@RequestParam Long categoryId) {
        return ServerResponseEntity.success(categoryService.getInfo(categoryId));
    }

    @PostMapping
    @Operation(summary = "保存分类信息" , description = "保存分类信息")
    public ServerResponseEntity<Void> save(@Valid @RequestBody CategoryDTO categoryDTO) {
        if (!Objects.equals(Constant.PLATFORM_SHOP_ID, AuthUserContext.get().getTenantId()) && categoryDTO.getLevel() > CategoryLevel.SECOND.value()) {
            throw new LuckException("分类等级最高只能为二级分类");
        }
        Long shopId = AuthUserContext.get().getTenantId();
        Integer getSysType = AuthUserContext.get().getSysType();
        categoryDTO.setShopId(shopId);
        categoryService.save(categoryDTO);
        categoryService.removeCategoryCache(shopId, null, getSysType);
        return ServerResponseEntity.success();
    }

    @PutMapping
    @Operation(summary = "更新分类信息" , description = "更新分类信息")
    public ServerResponseEntity<Void> update(@Valid @RequestBody CategoryDTO categoryDTO) {
        Integer getSysType = AuthUserContext.get().getSysType();
        categoryService.update(categoryDTO);
        categoryService.removeCategoryCache(AuthUserContext.get().getTenantId(), categoryDTO.getCategoryId(), getSysType);
        return ServerResponseEntity.success();
    }

    @DeleteMapping
    @Operation(summary = "删除分类信息" , description = "根据分类信息id删除分类信息")
    public ServerResponseEntity<Void> delete(@RequestParam Long categoryId) {
        Integer sysType = AuthUserContext.get().getSysType();
        CategoryVO category = categoryService.getById(categoryId);
        Long shopId = AuthUserContext.get().getTenantId();
        if (!Objects.equals(category.getShopId(), shopId)) {
            throw new LuckException(ResponseEnum.UNAUTHORIZED);
        }
        categoryService.deleteById(categoryId, shopId);
        if (Objects.equals(sysType, SysTypeEnum.PLATFORM.value())){
            categoryService.removeCategoryCache(category.getShopId(), categoryId, SysTypeEnum.MULTISHOP.value());
            categoryService.removeCategoryCache(category.getShopId(), categoryId, SysTypeEnum.PLATFORM.value());
            categoryService.removeCategoryCache(category.getShopId(), categoryId, SysTypeEnum.SUPPLIER.value());
        }else if (Objects.equals(sysType, SysTypeEnum.MULTISHOP.value())){
            categoryService.removeCategoryCache(category.getShopId(), categoryId, SysTypeEnum.MULTISHOP.value());
        }else if(Objects.equals(sysType, SysTypeEnum.SUPPLIER.value())) {
            categoryService.removeCategoryCache(category.getShopId(), categoryId, SysTypeEnum.SUPPLIER.value());
        }
        return ServerResponseEntity.success();
    }

    @GetMapping("/platform_categories")
    @Operation(summary = "获取平台所有的分类信息" , description = "获取所有的分类列表信息")
    public ServerResponseEntity<List<CategoryAppVO>> platformCategories() {
        return ServerResponseEntity.success(categoryService.platformCategories());
    }

    @GetMapping("/shop_categories")
    @Operation(summary = "获取店铺所有的分类信息" , description = "获取店铺所有的分类信息")
    public ServerResponseEntity<List<CategoryAppVO>> shopCategories() {
        return ServerResponseEntity.success(categoryService.list(AuthUserContext.get().getTenantId()));
    }

    @GetMapping("/enable_categories")
    @Operation(summary = "获取平台/店铺启用的分类信息" , description = "仅获取启用的分类，以及包含三级分类的分类信息")
    public ServerResponseEntity<List<CategoryAppVO>> enableCategories(Long shopId) {
        if (Objects.isNull(shopId) || !Objects.equals(shopId, Constant.PLATFORM_SHOP_ID)) {
            shopId = AuthUserContext.get().getTenantId();
        }
        List<CategoryAppVO> categories = categoryService.shopCategoryList(shopId, I18nMessage.getLang());
        List<CategoryAppVO> categoryList = new ArrayList<>();
        for (CategoryAppVO primaryCategoryVO : categories) {
            categoryList.add(primaryCategoryVO);
            if (!Objects.equals(shopId, Constant.PLATFORM_SHOP_ID)) {
                categoryList.addAll(primaryCategoryVO.getCategories());
                continue;
            }
            for (CategoryAppVO secondaryCategory : primaryCategoryVO.getCategories()) {
                categoryList.add(secondaryCategory);
                categoryList.addAll(secondaryCategory.getCategories());
            }
        }
        return ServerResponseEntity.success(categoryList);
    }

    @PutMapping(value = "/category_enable_or_disable")
    @Operation(summary = "分类的启用或禁用" , description = "分类的启用或禁用")
    public ServerResponseEntity<Boolean> categoryEnableOrDisable(@RequestBody CategoryDTO categoryDTO) {
        Integer sysType = AuthUserContext.get().getSysType();
        List<Long> categoryIds = categoryService.categoryEnableOrDisable(categoryDTO, sysType);
        // 批量更新
        Long tenantId = AuthUserContext.get().getTenantId();
        if (CollUtil.isNotEmpty(categoryIds)) {
            categoryIds.forEach(id -> categoryService.removeCategoryCache(tenantId, id, sysType));
        }
        return ServerResponseEntity.success();
    }

    @GetMapping("/sold_excel")
    @Operation(summary = "导出excel" , description = "导出分类excel")
    public ServerResponseEntity<Void> spuSoldExcel(HttpServletResponse response) {
        Long shopId = AuthUserContext.get().getTenantId();
        List<CategoryExcelVO> list = categoryService.listExcel(shopId);
        ExcelUtil.soleExcel(response, list, CategoryExcelVO.EXCEL_NAME, CategoryExcelVO.MERGE_ROW_INDEX, CategoryExcelVO.MERGE_COLUMN_INDEX,  CategoryExcelVO.class);
        return ServerResponseEntity.success();
    }
}
